from time import sleep

from apscheduler.schedulers.background import BackgroundScheduler

from constant import JINGDONG
from tables.shop_report import shop_report
from tables.sk_account_info import sk_account_info
from tables.sk_shop_info import sk_shop_info
from tables.his_kpi import his_kpi
from webDrivers import web_drivers
from datetime import datetime
from flask import Flask
import time

app = Flask(__name__)

@app.route('/jd_his_data/<date>')
def his_data(date):
    # 使用datetime.strptime将字符串转换为datetime对象
    dt_obj = datetime.strptime(date, "%Y-%m-%d")
    # 使用time.mktime将datetime对象转换为时间戳
    timestamp = int(time.mktime(dt_obj.timetuple()))

    get_his_data(timestamp)
    return "end-----"

def cron_his_data():
    print("his_data start")
    timestamp = int(time.time())
    # 东八区
    today = timestamp - (timestamp % 86400) - 3600 * 8
    # 获取昨天的日期
    yesterday = today - 86400
    get_his_data(yesterday)
    print("his_data end")

def get_his_data(timestamp):
    hisKpi = his_kpi()
    shopReport = shop_report()

    # 删除历史数据(报告数据)
    start_time = (timestamp - (86400 * 2)) * 1000
    end_time = timestamp * 1000
    hisKpi.delete_his_data(platform=JINGDONG, start_time=start_time, end_time=end_time)
    shopReport.delete_data(platform=JINGDONG, start_time=start_time, end_time=end_time)

    # 店铺信息
    shop = sk_shop_info()
    shopList = shop.find_shop_list(platform=JINGDONG)

    # 子账号信息
    account = sk_account_info()
    shopId = [row[0] for row in shopList]
    accountList = account.list_shop_account(shop_id=shopId)

    retryShop = shop_data(shop_list=shopList, accounts=accountList, timestamp=timestamp)

    # 从试机制
    retry = 0
    while len(retryShop) > 0 and retry < 4:
        retryShop = shop_data(shop_list=retryShop, accounts=accountList, timestamp=timestamp)
        retry += 1


def shop_data(shop_list, accounts, timestamp):
    retryShop = []
    for shop in shop_list:
        # 账号列表
        account_list = []
        for account in accounts:
            if account.shop_id == shop[0]:
                account_list.append(account)

        webdriver = web_drivers(shop, account_list)
        shop = webdriver.process(timestamp=timestamp)
        if shop:
            retryShop.append(shop)
    return retryShop

# 创建scheduler实例
scheduler = BackgroundScheduler()
# 添加定时任务
scheduler.add_job(cron_his_data, 'cron', hour=9, minute=10)
# 启动scheduler
scheduler.start()

if __name__ == '__main__':
    # (332, '嗨购姐黄牛肉批发', None, None, None, 'sksf25@shuke.vip', 'Qwe123456', '', datetime.datetime(2024, 4, 28, 19, 21, 49), '', datetime.datetime(2024, 4, 29, 15, 24, 2), None, '0', 107, None, '21,22,', '1', '登录错误', 1, '0', '罗双,刘远军,', 3, '107,', '总部五分部,', '10,', '杨邦智,', '33,', '张文娜,', None, '', 0, None, None)
    app.run(port=5600, debug=True)